package cn.com.yang.es;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;

/**
 * es搜索案例
 * TODO
 * @author yangyijin
 * @since 2024年1月6日-下午4:20:24
 */
public class EsSearchDemo {
	public static void main(String[] args) {
		search();
	}

	private static void search() {
		//创建搜索请求对象
		SearchRequest searchRequest = new SearchRequest("your_index_name");
		//构建查询条件
		SearchSourceBuilder sourceBuilder =new SearchSourceBuilder();
		sourceBuilder.from(0);//索引从0开始
		sourceBuilder.size(10);//每次返回10条
		sourceBuilder.timeout(new TimeValue(60,TimeUnit.SECONDS));//查询超时时间
		sourceBuilder.query(QueryBuilders.matchAllQuery());//查询条件
		sourceBuilder.sort("fieldName",SortOrder.ASC);//按字段排序
		searchRequest.source(sourceBuilder);
		// 开始查询
		HttpHost host = new HttpHost("localhost",9400);
		RestClientBuilder clientBuilder = RestClient.builder(host);
		try(RestHighLevelClient client = new RestHighLevelClient(clientBuilder)){
			SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
			//处理返回结果集
			for(SearchHit hit: response.getHits()) {
				String id = hit.getId();
				Map<String,Object> sourceMap = hit.getSourceAsMap();
				System.out.println("id:"+id);
				System.out.println("document:"+sourceMap);
			}
		}catch(Exception e) {
			e.printStackTrace();
		}
	}
}
